package com.example.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.example.net.event.Event
import com.example.net.event.bus
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
abstract class BaseView<B:ViewDataBinding,VM:BaseViewModel<*,*>>:AppCompatActivity() {
	val types by lazy {
		(javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
	}
	val binding:B by lazy {
		val clazz = types[0] as Class<B>
		clazz.getMethod("inflate",LayoutInflater::class.java).invoke(null,layoutInflater) as B
	}
	val viewModel:VM by lazy {
		val clazz = types[1] as Class<VM>
		ViewModelProvider(this)[clazz]
	}
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(binding.root)
		observable()
		initData()
		initView()
	}
	
	private fun observable() {
		val methods = javaClass.declaredMethods
		for (method in methods){
			val event = method.getAnnotation(Event::class.java)
			if(event != null){
				bus.observe(this){
					if(it.first == event.value){
						method.invoke(this,it.second)
					}
				}
			}
		}
	}
	
	abstract fun initView()
	
	abstract fun initData()
}